<template>
  <div>
    <en-table-layout
      pagination
      :tableData="tableData"
      :loading="loading">
        <div slot="toolbar" class="inner-toolbar">
          <div class="toolbar-btns">
            <el-button  @click="addDict()" type="primary">新增</el-button>
          </div>
          <div class="toolbar-search">
            <en-table-search
              @search="searchEvent"
              @advancedSearch="advancedSearchEvent"
              advanced
              placeholder="请输入字典描述">>
              <template slot="advanced-content">
                <el-form ref="advancedForm" :model="advancedForm" label-width="80px">
                  <el-form-item label="字典类型">
                    <el-select v-model="advancedForm.type" clearable>
                        <el-option
                            v-for="(item, index) in typeData"
                            :key="index"
                            :label="item"
                            :value="item"></el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
              </template>
            </en-table-search>
          </div>
        </div>
        <template slot="table-columns">
        <!--类型-->
        <el-table-column prop="type" label="类型"/>
        <!--标签名-->
        <el-table-column prop="label" label="标签名"/>
        <!--键值-->
        <el-table-column prop="value" label="键值"/>
        <!--归类-->
        <el-table-column prop="classify" label="归类">
          <template slot-scope="scope">
          <div>{{scope.row.classify | filterDict('dict_type')}}</div>
          </template>
        </el-table-column>
        <!--描述-->
        <el-table-column prop="description" label="描述"/>
        <!--排序-->
        <el-table-column prop="sort" label="排序"/>
        <!--操作 -->
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <div class="opera-row">
                <el-button 
                    size="mini"
                    type="primary"
                    @click="showEdit(scope.row.id)">修改</el-button>
                <el-button 
                    size="mini"
                    type="danger"
                    @click="Del_DataDict(scope.$index, scope.row)">删除</el-button>
            </div>
        </template>
        </el-table-column>
      </template>
      <!-- 分页 -->
      <el-pagination
        v-if="tableData"
        slot="pagination"
        @size-change="handlePageSizeChange"
        @current-change="handlePageCurrentChange"
        :current-page="pageData.page_no"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageData.page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageData.data_total">
      </el-pagination>
    </en-table-layout> 
    <!-- dialogMht begin -->
  <el-dialog
    :title="titleMap[dialogStatus] + '字典'"
    width="420px"
    :close-on-click-modal="false"
    :visible.sync="dialogDict">
    <el-form
      ref="dictForm"
      class="dictForm"
      label-width="90px"
      size="small"
      :rules="rulesDict"
      :model="dictForm">
      <el-form-item v-if="dialogStatus==='edit'" v-show="false">
        <el-input class="w220" type="hidden" v-model="dictForm.id"></el-input>
      </el-form-item>
      <el-form-item label="类型：" prop="type">
        <el-input type="text" v-model="dictForm.type" placeholder="请输入类型"></el-input>
      </el-form-item>
      <el-form-item label="标签名：" prop="label">
        <el-input type="text" v-model="dictForm.label" placeholder="请输入标签名"></el-input>
      </el-form-item>
      <el-form-item label="键值：" prop="value">
        <el-input type="text" v-model="dictForm.value" placeholder="请输入键值"></el-input>
      </el-form-item>
      <el-form-item label="归类：" prop="classify" >
        <dg-select clearable dictType="dict_type" v-model="dictForm.classify" :defaultValue="dictForm.classify"></dg-select>
      </el-form-item>
      <el-form-item label="排序：" prop="sort">
        <el-input type="text" v-model="dictForm.sort" clearable placeholder="菜单排序"></el-input>
      </el-form-item>
      <el-form-item label="描述：">
        <el-input type="text" v-model="dictForm.description" placeholder="请输入描述"></el-input>
      </el-form-item>
      <el-form-item label="备注：" prop="remarks">
        <el-input type="textarea" rows="2" v-model="dictForm.remarks" placeholder="请输入字典描述，50字内，非必填" maxlength="50"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" type="primary" :loading="dialogLoading" @click="dictSubmit()">确 定</el-button>
      <el-button size="small" @click="dialogDict = false">取 消</el-button>
    </div>
  </el-dialog>
  <!-- dialogMht end -->
  </div>
</template>
<script>
import { GET_DataDict, queryAllType, Del_DataDict, add_DataDict, udp_DataDict, query_DictById } from '@/api/dict'
import { getDictData, filterShowDict } from '@/common/filter-show';

export default {
  name: 'data-dict',
  data() {
    return {
      //下拉框 
      typeData: [],

      // 搜索
      //   searchForm: { 
      //     type: undefined, // 字典类型
      //     description: undefined // 字典描述
      //   }, 

      /** 高级搜索数据 */
      advancedForm: {
        type: undefined // 字典类型
      },

      // 列表loading状态
      loading: false,

      // 列表参数
      params: {
        page_no: 1,
        page_size: 10
      },
      // 列表数据
      tableData: [],

      // 分页数据
      pageData: [],
      dialogLoading: false,
      dialogDict: false, // 字典弹层
      dialogStatus: 'new', // 默认新增
      titleMap: {
        'new': '新增',
        'edit': '修改'
      },
      dictForm: { // 字典弹层表单
        id: undefined,
        type: undefined, // 类型
        label: undefined, // 标签名
        value: undefined, // 键值
        classify: undefined, // 归类
        sort: undefined,
        description: undefined, // 描述
        remarks: undefined // 备注
      },
      rulesDict: { // 字典弹层表单规则
        type: [
          { required: true, message: '请输入类型', trigger: 'blur' }
        ],
        label: [
          { required: true, message: '请输入标签名', trigger: 'blur' }
        ],
        value: [
          { required: true, message: '请输入键值', trigger: 'blur' }
        ],
        classify: [
          { required: true, message: '请选择归类', trigger: 'change' }
        ],
        sort: [
          { required: true, message: '请输入排序', trigger: 'blur' }
        ]
      }
    }
  },
  filters: {
    // 字典显示转换
    filterDict (_stateVal, _dictType) {
      return filterShowDict(_dictType, _stateVal);
    }

  },
  mounted () {
    // 获取格式化字典数据
    getDictData('dict_type');

    // 初始化列表数据 
    this.GET_DataDict();

    // 初始化数据字典类型 
    this.queryAllType();
  },
  methods: {
    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size
      this.GET_DataDict()
    },

    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page
      this.GET_DataDict()
    },
 
    /** 获取数据字典列表 */
    GET_DataDict() {
      this.loading = true;
      GET_DataDict(this.params).then(response => {
        this.loading = false;
        this.tableData = response.data;
        this.pageData = {
          page_no: response.page_no,
          page_size: response.page_size,
          data_total: response.data_total
        }
      }).catch(() => {
        this.loading = false;
      })
    },

    /** 获取全部数据字典 */
    queryAllType() {
      this.loading = true;
      queryAllType().then(response => {
        this.loading = false;
        this.typeData = response;
      })
        .catch(() => {
          this.loading = false;
        })
    },

    /** 搜索事件触发 */
    searchEvent(data) {
      this.params = {
        ...this.params,
        description: data
      }
      this.params.page_no = 1
      Object.keys(this.advancedForm).forEach(key => delete this.params[key])
      this.GET_DataDict()
    },

    /** 高级搜索事件触发 */
    advancedSearchEvent() {
      this.params = {
        ...this.params,
        ...this.advancedForm
      }
      delete this.params.keyword
      this.params.page_no = 1
      this.GET_DataDict()
    },    

    /** 添加 */
    addDict () {
      this.dialogStatus = 'new';
      this.dialogDict = true;
      this.dictForm.id = undefined;
    },
    
    /** 修改 */
    showEdit (_id) {
      this.resetForm('dictForm');
      this.dialogStatus = 'edit';
      this.dialogDict = true;
      query_DictById(_id).then(res => {
        let _useData = res;
        if (_useData) {
          this.dialogStatus = 'edit';
          this.dialogDict = true;
          this.dictForm = {
            'id': _useData.id,
            'type': _useData.type,
            'label': _useData.label,
            'value': _useData.value,
            'description': _useData.description,
            'sort': _useData.sort,
            'classify': _useData.classify,
            'remarks': _useData.remarks
          }
        }
      }).catch(() => {
        this.loading = false;
      });
    },

    /** 确定按钮 */
    dictSubmit () {
      this.$refs['dictForm'].validate((valid) => {
        if (valid) {
          this.dialogLoading = true;
          let _formData = this.dictForm;
          let _params = {
            'type': _formData.type,
            'label': _formData.label,
            'value': _formData.value,
            'classify': _formData.classify,
            'sort': _formData.sort,
            'description': _formData.description,
            'remarks': _formData.remarks
          };
          let _fileName = add_DataDict; // 请求类别
          if (_formData.id || _formData.id === 0) { // 存在id 即为修改
            _fileName = udp_DataDict;
            _params.id = _formData.id;
          }
          _fileName(_params).then(res => {
            console.log("res" +JSON.stringify(res));
            this.$message({ message: res.message, type: 'success' });
            this.dialogDict = false;
            this.dialogLoading = false;
            this.loading = false;
            if (_formData.id || _formData.id === 0) {
              this.resetForm('dictForm');
            }
            // 初始化搜索查询
            this.queryAllType();
            // 查询列表
            this.GET_DataDict();
          }).catch(() => {
            this.dialogLoading = false;
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    /**删除数据字典 */
    Del_DataDict(index, row) {
      this.$confirm('确定要删除吗？', '提示', { type: 'warning' }).then(() => {
        Del_DataDict(row.id).then((response) => {
          this.$message.success(response.message);
          this.GET_DataDict();
        })
      }).catch(() => {})
    },
    
    /** 改变状态 */
    changeType(val) {
      this.params = {
        ...this.params,
        status: val
      }
      this.GET_DataDict()
    },
    /** 条件重置 */
    resetForm (formName) {
      if (this.$refs[formName] !== undefined) {
        this.$refs[formName].resetFields();
      }
    }
  }
}
</script>
<style type="text/scss" lang="scss" scoped>
  /deep/ .el-table td:not(.is-left) {
    text-align: center;
  }

  .inner-toolbar {
    display: flex;
    width: 100%;
    justify-content: space-between;
    padding: 0 20px;
  }
  .conditions {
    span {
      font-size: 10px;
      color: #666;
    }
     width: 100%;
  }
</style>
